package com.example.common.component;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.common.control.ICallback;
import com.example.common.network.ImgLoaderReq;
import com.example.common.network.RetrofitServiceManager;

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ImgLoaderCtrlCom{
    //操作请求实例
    private ImgLoaderReq imgLoaderReq;

    //构造函数，加载实例
    public ImgLoaderCtrlCom(){
        imgLoaderReq= RetrofitServiceManager.getInstance().create(ImgLoaderReq.class);
    }

    /**
     * 获取图片
     * @param url 图片链接
     * @param callback 回调函数
     */
    public void getImg(String url, ICallback callback) {
        //创建请求
        Call<ResponseBody> call=imgLoaderReq.getImg(url);
        //发出请求
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()){//200到300
                    try {
                        byte[] bytes=response.body().bytes();
                        Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                        callback.onSuccess(bitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    //500时返回错误
                    callback.onFailed(response.errorBody().toString());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callback.onFailed("网络错误。");
            }
        });
    }


    public void getGame(ICallback callback) {
        Call<ResponseBody> call = imgLoaderReq.getGame();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                callback.onSuccess(response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callback.onFailed("失败了");
            }
        });
    }
}
